#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>

void read_pipe(char *command)
{
	char buffer[100];
	char item[10][20];
	char *word;
	char *argv[5];

	strcpy(buffer, command);
	word = strtok(buffer, " ");
	int i = 0, j, n;
	while(word != NULL) {
		strcpy(item[i++], word);
		word = strtok(NULL, " ");
	}
	for(j = 0; j < i; ++j) {
		argv[j] = (char *)malloc(sizeof(char)*20);
		strcpy(argv[j], item[j]);
	}
	argv[j] = NULL;
	
	pid_t pid;
	int fd[2];
	pipe(fd);
	pid = fork();
	if(pid == 0) {
		dup2(fd[1], 1);
		close(fd[0]);
		close(fd[1]);
		int error = execvp(argv[0], argv);
		if(error < 0) {
			perror("execvp");
		}
		exit(0);
	}
	close(fd[1]);
        char buf[10];
	bzero(buf, sizeof(buf));
	while(read(fd[0], buf, sizeof(buf)-1)) {
		printf("%s",buf);
		bzero(buf, sizeof(buf));
	}
        for(j = 0; j<=i; ++j) {
		free(argv[j]);
	}

}
int main()
{
    printf("--------------------------------------------------\n");
    read_pipe("echo HELLO WORLD");
    printf("--------------------------------------------------\n");
    read_pipe("ls /");
    printf("--------------------------------------------------\n");
    return 0;
}
